package com.winai.launcher.view.set;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.arialyy.aria.core.Aria;
import com.baidu.location.BDLocation;
import com.ks.projectbasictools.base.SimpleView;
import com.ks.projectbasictools.retrofit.HttpResponseListener;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.db.CurrentLocation;
import com.winai.launcher.bean.requestBean.DevicePushVersionBean;
import com.winai.launcher.bean.responseEntity.DevicePushVersionEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.constant.HttpUrls;
import com.winai.launcher.constant.MainRouter;
import com.winai.launcher.manager.BdLocationManager;
import com.winai.launcher.manager.VideoManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.service.heartBeat.HeartBeatService;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.DialogUtils;
import com.winai.launcher.utils.FileUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.OpenAppUtils;
import com.winai.launcher.utils.ScreenUtils;
import com.winai.launcher.utils.ServerUtils;
import com.winai.launcher.utils.Tools;
import com.winai.launcher.utils.VersionUtils;

import org.litepal.LitePal;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/22 0022
 * 说明：关于设备
 */
public class SetAboutUsActivity extends BaseActivity {
    private static final String TAG = "SetAboutUsActivity";

    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.tv_deviceName)
    TextView tvDeviceName;
    @BindView(R.id.tv_deviceLocation)
    TextView tvDeviceLocation;
    @BindView(R.id.tv_deviceVersion)
    TextView tvDeviceVersion;
    @BindView(R.id.tv_uuid)
    TextView tvUuid;
    @BindView(R.id.tv_wifiMac)
    TextView tvWifiMac;
    @BindView(R.id.tv_bluetoothMac)
    TextView tvBluetoothMac;
    @BindView(R.id.tv_checkVersion)
    TextView tvCheckVersion;

    private Context mContext = this;
    private Animation loadingAnimation;
    private CurrentLocation currentLocation1 = new CurrentLocation();
    private ImageView ivLoading;
    private Dialog loadingDialog, newestVersionTipDialog, findNewVersionTipDialog;
    private SpeechReceiver speechReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_about_us);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        notifyBroadcast();
        requestPermiss();
        String titleName = getIntent().getStringExtra("titleName");
        strTitle.setText(titleName);

        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());

        //初始化思必驰广播
        speechReceiver = new SpeechReceiver(this);
        speechReceiver.init();

        String newestVersionCode = VersionUtils.getNewestVersionCode(mContext);
        VersionUtils.getAiyishengVersionName(mContext);
        if (newestVersionCode.contains("unknown")) {
            setVersionCode();
        } else {
            tvDeviceVersion.setText(newestVersionCode);
        }
        tvDeviceName.setText(R.string.app_name);
        updateViewData();//显示当前位置
        //Uuid
        tvUuid.setText(BaseUtils.getDeviceId());
        //WifiMac
        tvWifiMac.setText(BaseUtils.getMac());
        //BluetoothMac
        if (Constant.bluetoothLinked) {
            tvBluetoothMac.setText(Constant.operationDevice.getAddress());
        } else {
            tvBluetoothMac.setText("蓝牙未连接");
        }
    }

    int count = 0;

    /**
     * @date 2020/10/12
     * @desc 设置版本号
     */
    @SuppressLint("SetTextI18n")
    private void setVersionCode() {
        new Thread(() -> {
            String newestVersionCode = VersionUtils.getNewestVersionCode(mContext);
            while (newestVersionCode.contains("unknown") && count < 5) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        tvDeviceVersion.setText("第" + count + "次尝试获取版本号");
                    }
                });
                newestVersionCode = VersionUtils.getNewestVersionCode(mContext);
            }
            String finalNewestVersionCode = newestVersionCode;
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    tvDeviceVersion.setText(finalNewestVersionCode);
                }
            });
        }).start();
    }

    /**
     * @date 2020/10/10
     * @desc 发送广播查询语音内核版本
     */
    private void notifyBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_GET_VERSION);
        mContext.sendBroadcast(intent);
    }

    private void requestPermiss() {
        if (!hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) || !hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            requestPermission(111, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            requestPermission(111, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    /**
     * 说明：更新视图
     */
    @SuppressLint("SetTextI18n")
    private void updateViewData() {
        CurrentLocation last = LitePal.findLast(CurrentLocation.class);
        if (last != null) {
            tvDeviceLocation.setText(last.getLocality());
        }
        getLocation();
    }

    private void getLocation() {
        BdLocationManager.getInstance().onStart(location -> {
            if (location == null) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
                return;
            }
            if (location.getLocType() == BDLocation.TypeCriteriaException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
            } else {
                //获取经度信息
                double longitude = location.getLongitude();
                //获取维度信息
                double latitude = location.getLatitude();
                String city = !TextUtils.isEmpty(location.getAddress().city)
                        ? location.getAddress().city
                        : "";
                String province = location.getAddress().province == null
                        ? city.replace("市", "")
                        : location.getAddress().province;
                String district = location.getAddress().district;
                if (longitude == 0 || latitude == 0 || longitude == 4.9E-324 || latitude == 4.9E-324) {
                    Log.e(TAG, "获取位置失败，当前信息可能有误");
                    return;
                }
                //获取经纬度位置信息，存入本地数据库缓存
                currentLocation1.setLatitude(latitude);
                currentLocation1.setLongitude(longitude);
                currentLocation1.setAdminArea(province);
                currentLocation1.setLocality(city);
                currentLocation1.setSubLocality(district);
                currentLocation1.saveOrUpdate("id = 1");

                SetAboutUsActivity.this.runOnUiThread(() -> {
                    String locality = city;
                    if (!TextUtils.isEmpty(locality)) {
                        if (locality.contains("省") || locality.contains("市") || locality.contains("区")) {
                            locality = locality.replace("省", "");
                            locality = locality.replace("市", "");
                            locality = locality.replace("区", "");
                        }
                        tvDeviceLocation.setText(locality);
                    } else {
                        tvDeviceLocation.setText("未知");
                    }
                });
            }
        });
    }

    private void checkVersion() {
        showLoading();
        DevicePushVersionBean mDevicePushVersionBean = new DevicePushVersionBean();
//        mDevicePushVersionBean.setName("X106F-DEV-B1.0.1-Provision-20210225-09:51");
        mDevicePushVersionBean.setName(BaseUtils.getSystemVersion());
        mDevicePushVersionBean.setEquipmentId(BaseUtils.getDeviceId());
        ServerUtils.requestJsonPost(HttpUrls.CHECK_VERSION, null, mDevicePushVersionBean
                , new HttpResponseListener<DevicePushVersionEntity>() {
                    @Override
                    public void onResponse(DevicePushVersionEntity var1, boolean isCache) {
                        dismissLoadingDialog();
                        if (isCache) {
                            return;
                        }
                        if (var1.getData() != null) {
                            //有更新
                            LogUtils.i("发现ROM新版本");
                            boolean mandatory = var1.getData().isMandatory();//true：强制更新；false：非强制更新
                            HeartBeatService.md5 = var1.getData().getMd5();
                            showFindNewVersionDialog(var1.getData().getVersionName(), var1.getData().getPath());
//                            UpgradeProgressManager.getInstance(mContext).setVersionName(var1.getData().getVersionName());
//                            UpgradeWindowManager.getInstance(mContext, var1.getData().getPath()).showTip();
                        } else {
                            LogUtils.i("无ROM更新");
                            showNewestVersionTip();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        super.onError(code, msg);
                        dismissLoadingDialog();
                    }
                });
    }

    private void showFindNewVersionDialog(String versionName, String path) {
        //禁止唤醒
        NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext, false);
        //禁止下拉
        NotifyReceiverUtils.notifyPulldownReceiver(mContext, false);
        //通知QQ音乐暂停
        NotifyReceiverUtils.notifyControlQQMusic(mContext, Constant.MediaControllerStop, null);
        //关闭曲艺
        VideoManager.getInstance(mContext).stop(true);

        SimpleView view = new SimpleView(mContext, R.layout.dialog_find_new_version);
        initFindNewVersionTipView(view, versionName, path);
        findNewVersionTipDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), false);
        Tools.showDialog(findNewVersionTipDialog);
    }

    private void initFindNewVersionTipView(SimpleView view, String versionName, String mPath) {
        TextView tvVersoin = view.findViewById(R.id.tv_version);
        tvVersoin.setText(versionName);
        view.findViewById(R.id.tv_update).setOnClickListener(v -> {
            if (mPath == null) {
                ToastKs.show(mContext, "更新文件为空，请联系后台管理员");
                return;
            }
            boolean fileExists = FileUtils.isFileExists(new File(FileUtils.getLocalPath(mPath)));
            LogUtils.d("系统更新文件是否存在 fileExists = " + fileExists);
            if (!fileExists) {
                downloadFile(mPath);
            } else {
                GlobalPublisher.Notify(GlobalPublisher.DOWNLOAD_ROM_COMPLETE, mPath);
            }
            hideFindNewVersionTip();
        });
    }

    private void downloadFile(String path) {
        /**文件数量大于两个时，删除文件夹下所有内容*/
        List<File> fileList = FileUtils.getFile(new File(DirectoryConstant.ROM_PATH));
        if (fileList != null && fileList.size() > 2) {
            FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
        }
        long taskId = Aria.download(this)
                .load(path)     //读取下载地址
                .setFilePath(FileUtils.getLocalPath(path)) //设置文件保存的完整路径
                .ignoreFilePathOccupy()
                .create();   //创建并启动下载
    }

    private void hideFindNewVersionTip() {
        Tools.dimssDialog(findNewVersionTipDialog);
    }

    /**
     * @date 3/16/21
     * @desc 当前已是最新版本——提示
     */
    private void showNewestVersionTip() {
        SimpleView view = new SimpleView(mContext, R.layout.dialog_newest_version);
        initNewestTipView(view);
        newestVersionTipDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), true);
        Tools.showDialog(newestVersionTipDialog);
    }

    private void initNewestTipView(SimpleView view) {
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideNewestVersionTip();
            }
        });
    }

    private void hideNewestVersionTip() {
        Tools.dimssDialog(newestVersionTipDialog);
    }

    /**
     * @date 3/16/21
     * @desc 正在检查更新——loading
     */
    private void showLoading() {
        SimpleView view = new SimpleView(mContext, R.layout.dialog_upgrade_loading);
        initView(view);
        loadingDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), false);
        Tools.showDialog(loadingDialog);
    }

    private void initView(SimpleView view) {
        ivLoading = view.findViewById(R.id.iv_loading);
        runOnUiThread(() -> {
            ivLoading.setVisibility(View.VISIBLE);
            ivLoading.startAnimation(loadingAnimation);
        });
    }

    private void dismissLoadingDialog() {
        Tools.dimssDialog(loadingDialog);
        runOnUiThread(() -> {
            ivLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.rl_version, R.id.tv_checkVersion, R.id.tv_law})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.rl_version:
                Intent i = new Intent(mContext, VersionDetailActivity.class);
                startActivity(i);
                break;
            case R.id.tv_checkVersion:
                //检查更新
                checkVersion();
                break;
            case R.id.tv_law:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_LEGAL_AGREEMENT, ".法律协议@");
                break;
        }
    }

    private static class SpeechReceiver extends BroadcastReceiver {
        private WeakReference<SetAboutUsActivity> setAboutUsActivityWeakReference;

        public SpeechReceiver(SetAboutUsActivity setAboutUsActivity) {
            this.setAboutUsActivityWeakReference = new WeakReference<>(setAboutUsActivity);
        }

        public void init() {
            IntentFilter mFilter = new IntentFilter();
            mFilter.addAction(Constant.ACTION_DIALOG_STATUS);
            setAboutUsActivityWeakReference.get().registerReceiver(this, mFilter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null) return;
            if (intent.getAction().equals(Constant.ACTION_DIALOG_STATUS)) {
                setAboutUsActivityWeakReference.get().hideNewestVersionTip();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(speechReceiver);
    }
}
